package com.syh.jn.scm.service.impl.upstream.sale;

import cn.redscarf.commons.util.other.ExtAssert;
import cn.redscarf.commons.wrapper.Restrictions;
import cn.redscarf.commons.wrapper.Wrapper;
import com.alibaba.dubbo.config.annotation.Service;
import com.syh.core.ddd.event.annotation.DomainEventHandle;
import com.syh.core.ddd.infrastructure.repository.AggregateRepository;
import com.syh.core.ddd.service.AbstractServiceImpl;
import com.syh.jn.scm.domain.driver.entity.logistics.DriverLogisticsBill;
import com.syh.jn.scm.domain.driver.event.DriverLogisticsBillEvent;
import com.syh.jn.scm.domain.upstream.entity.finance.UpStatementAccountBill;
import com.syh.jn.scm.domain.upstream.entity.logistics.UpLogisticsBill;
import com.syh.jn.scm.domain.upstream.entity.sale.UpSaleReturnOrder;
import com.syh.jn.scm.domain.upstream.event.UpLogisticsBillEvent;
import com.syh.jn.scm.domain.upstream.event.UpStatementAccountBillEvent;
import com.syh.jn.scm.domain.upstream.repository.logistics.UpLogisticsBillRepository;
import com.syh.jn.scm.domain.upstream.repository.sale.UpSaleReturnOrderRepository;
import com.syh.jn.scm.dto.support.FilesDto;
import com.syh.jn.scm.dto.upstream.sale.UpSaleReturnOrderVo;
import com.syh.jn.scm.service.api.upstream.finance.enums.UpStatementAccountBillEnum;
import com.syh.jn.scm.service.api.upstream.logistics.enums.UpLogisticsBillEnum;
import com.syh.jn.scm.service.api.upstream.sale.UpSaleReturnOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class UpSaleReturnOrderServiceImpl extends AbstractServiceImpl<Object, Object, UpSaleReturnOrderVo, UpSaleReturnOrder, Long> implements UpSaleReturnOrderService {

  @Autowired
  private UpSaleReturnOrderRepository upSaleReturnOrderRepository;
  @Autowired
  private UpLogisticsBillRepository upLogisticsBillRepository;

  @Override
  protected AggregateRepository<UpSaleReturnOrder, Long> getAggregateRepository() {
    return upSaleReturnOrderRepository;
  }

  /**
   * 确认订单
   *
   * @param id 订单id
   */
  @Override
  public void confirm(Long id) {
    UpSaleReturnOrder entity = idIsNull(id);
    entity.confirm();
    upSaleReturnOrderRepository.update(entity);
  }

  @Override
  public void cancelConfirm(Long id) {
    UpSaleReturnOrder entity = idIsNull(id);
    entity.cancelConfirm();
    upSaleReturnOrderRepository.update(entity);
  }

  /**
   * 取消订单
   *
   * @param id 订单id
   */
  @Override
  public void cancel(Long id) {
    UpSaleReturnOrder entity = idIsNull(id);
    entity.cancel();
    upSaleReturnOrderRepository.update(entity);
  }

  /**
   * 校验订单是否存在
   *
   * @param id
   * @return
   */
  private UpSaleReturnOrder idIsNull(Long id) {
    ExtAssert.notNull(id, "id不能为空");
    UpSaleReturnOrder entity = upSaleReturnOrderRepository.getById(id);
    ExtAssert.notNull(entity, "订单不存在");
    return entity;
  }

  /**
   * 上传单据图片
   *
   * @param dto
   */
  @Override
  public void upload(FilesDto dto) {
    UpSaleReturnOrder order = idIsNull(dto.getId());
    order.upload(dto);
    upSaleReturnOrderRepository.upload(order);
  }

  /**
   * 消费者：监听物流单收货（修改收货数量）
   * @param bill
   */
  @DomainEventHandle(UpLogisticsBillEvent.UP_LOGISTICS_BILL_COLLECTED)
  protected void handleUpLogisticsBillCollected(UpLogisticsBill bill) {
    if (UpLogisticsBillEnum.ORDER_TYPE_RETURN_SALE.getStatus().equals(bill.getOrderType())) {
      UpSaleReturnOrder order = upSaleReturnOrderRepository.getById(bill.getOrderId());
      order.collect(bill);
      upSaleReturnOrderRepository.updateOrderAndItems(order);
    }
  }

  /**
   * 消费者：监听司机端物流单收货（修改收货数量）
   * @param bill
   */
  @DomainEventHandle(DriverLogisticsBillEvent.DRIVER_LOGISTICS_BILL_COLLECTED)
  protected void handleDriverLogisticsBillCollected(DriverLogisticsBill bill) {
    this.handleUpLogisticsBillCollected(upLogisticsBillRepository.getById(bill.getId()));
  }

  /**
   * 消费者：监听物流单取消收货（修改收货数量）
   * @param bill
   */
  @DomainEventHandle(UpLogisticsBillEvent.UP_LOGISTICS_BILL_UN_RECEIVED)
  protected void handleUpLogisticsBillUnReceived(UpLogisticsBill bill,UpLogisticsBill oldBill) {
    if (UpLogisticsBillEnum.ORDER_TYPE_RETURN_SALE.getStatus().equals(bill.getOrderType())) {
      UpSaleReturnOrder order = upSaleReturnOrderRepository.getById(bill.getOrderId());
      order.cancelCollect(bill);
      upSaleReturnOrderRepository.updateOrderAndItems(order);
    }
  }

  /**
   * 消费者：监听对账单（生成对账单状态和对账单号）
   *
   * @param bill
   */
  @DomainEventHandle(UpStatementAccountBillEvent.UP_STATEMENT_BILL_ACCOUNT_CREATED)
  protected void handleUpStatementBillAccountCreated(UpStatementAccountBill bill) {
    bill.getUpStatementAccountBillItems().forEach(billItem -> {
      if (billItem.getSourceType().equals(UpStatementAccountBillEnum.SOURCE_SALE_RETURN_ORD.getStatus())) {
        UpSaleReturnOrder saleReturnOrder = upSaleReturnOrderRepository.getById(billItem.getSourceId());
        saleReturnOrder.generating(bill.getId());
        upSaleReturnOrderRepository.updateStatus(saleReturnOrder);
      }
    });
  }

  /**
   * 消费者：监听对账单（修改对账单状态）
   *
   * @param bill
   */
  @DomainEventHandle(UpStatementAccountBillEvent.UP_STATEMENT_BILL_ACCOUNT_UPDATA)
  protected void handleUpStatementBillAccountUpdata(UpStatementAccountBill bill) {
    Wrapper wrapper = Wrapper.build();
    wrapper.append(Restrictions.eq("statementId", bill.getId()));
    List<UpSaleReturnOrder> upSaleReturnOrders = upSaleReturnOrderRepository.getList(wrapper);
    upSaleReturnOrders.forEach(upSaleOrder -> {
      upSaleOrder.cancelGenerating();
      upSaleReturnOrderRepository.updateStatus(upSaleOrder);
    });
    bill.getUpStatementAccountBillItems().forEach(billItem -> {
      if (billItem.getSourceType().equals(UpStatementAccountBillEnum.SOURCE_SALE_RETURN_ORD.getStatus())) {
        UpSaleReturnOrder upSaleReturnOrder = upSaleReturnOrderRepository.getById(billItem.getSourceId());
        upSaleReturnOrder.generating(bill.getId());
        upSaleReturnOrderRepository.updateStatus(upSaleReturnOrder);
      }
    });
  }

  /**
   * 消费者：监听对账单（删除对账单状态和对账单号）
   *
   * @param bill
   */
  @DomainEventHandle(UpStatementAccountBillEvent.UP_STATEMENT_BILL_ACCOUNT_DESTORY )
  protected void handleUpStatementBillAccountDestory(UpStatementAccountBill bill) {
    bill.getUpStatementAccountBillItems().forEach(billItem -> {
      if (billItem.getSourceType().equals(UpStatementAccountBillEnum.SOURCE_SALE_RETURN_ORD.getStatus())) {
        UpSaleReturnOrder saleReturnOrder = upSaleReturnOrderRepository.getById(billItem.getSourceId());
        saleReturnOrder.cancelGenerating();
        upSaleReturnOrderRepository.updateStatus(saleReturnOrder);
      }
    });
  }
}
